package com.chenjie.drools.drl;

import java.lang.reflect.Field;
import java.util.ArrayList; 
import java.util.List; 

import com.chenjie.drools.dao.primary.model.Property;

public class Main {
    public static void main(String[] args) {  
        String clazzName = "quality.student";
    	dynamicCreadFact(clazzName);  
    	List<Object> o = createFact(clazzName); 
	    execute(o);
    }
     
    public static List<Object> createFact(String clazzName) { 
        List<Object> os = new ArrayList<Object>();
    	try {
        	BeanManager beanManager = BeanManager.getInstance(); 
        	Class clazz = beanManager.getLoadedDynamicClass().get(clazzName);
		 	Object object = clazz.newInstance();
		 	Field name = clazz.getDeclaredField("name");
			name.setAccessible(true);
			name.set(object, "chenjie");
		 	Field age = clazz.getDeclaredField("age");
			age.setAccessible(true);
			age.set(object, 25);
			os.add(object);
		} catch (NoSuchFieldException | SecurityException | InstantiationException | IllegalAccessException e) { 
			e.printStackTrace();
		}
    	return os;
	}
    
    public static void dynamicCreadFact(String clazzName) { 
    	BeanManager beanManager = BeanManager.getInstance();
		String clazz = clazzName;   
		List<Property> properties = new ArrayList<Property>();
	    properties.add(new Property("name", "String"));
	    properties.add(new Property("age", "Integer"));
	    beanManager.create(clazz, properties);  
	}

    public static void execute(List<Object> os){
        DrlExecutor drlExecutor = DrlExecutor.getInstance(); 

        drlExecutor.execute(getDrl(), os);
    }

    public static String  getDrl(){
        String drl
                = "import quality.*;                  \r\n"
                + "rule if                        \r\n"
                + "when  \r\n" 
                + "  $p:student()               \r\n"
                + "then                           \r\n" 
                + " System.out.println( \"name:\" + $p.name);  \r\n" 
                + " System.out.println( \"age:\" + $p.age);  \r\n" 
                + "end;"; 
        return drl;
    }
}
